package problem39;

import java.util.ArrayList;
import java.util.List;

//39.组合总和
//https://leetcode.cn/problems/combination-sum/

class Solution2 {
    List<List<Integer>> ret = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    int sum = 0;
    int target;
    int[] nums;
    public List<List<Integer>> combinationSum(int[] candidates, int _target) {
        nums = candidates;
        target = _target;
        dfs(0);
        return ret;
    }
    public void dfs(int u) {
        if(sum == target) {
            ret.add(new ArrayList(path));
            return;
        }
        if(sum > target || u == nums.length) return;

        int count = (target - sum) / nums[u];
        for(int i = 0; i<=count; i++) {
            if(i != 0) {
                sum += nums[u];
                path.add(nums[u]);
            }
            dfs(u+1);
        }

        for(int i = 0; i<count; i++) {
            sum -= nums[u];
            path.remove(path.size()-1);
        }
    }
}